import Vue from 'vue'
import Router from 'vue-router'

Vue.use(Router)

// 固定的路由
export const constantRoutes = [
    {
        path: '/',
        component: () => import('@/views/Login'),
        meta: {title: '登录'},
    },
    {
        path: '/homepage',
        component: () => import('@/views/HomePage'),
        meta: {title: '主页'},
    },
    {
        path: '/upload',
        name: 'Upload',
        component: () => import('@/components/Upload'),
        meta: {title: '上传实案'},
    },
    {
        path: '/search',
        name: 'Search',
        component: () => import('@/components/Search'),
        meta: {title: '搜索'}
    },
    {
        path: '/detail',
        name: 'Detail',
        component: () => import('@/views/Detail'),
        meta: {title: '案例详情'}
    },
    {
        path: '/userManagement',
        name: 'UserManagement',
        component: () => import('@/views/UserManagement'),
        meta: {title: '用户管理'}
    },
    {
        path: '/review',
        name: 'Review',
        component: () => import('@/views/Review'),
        meta: {title: '实案审核'}
    },
    {
        path: '/favorite',
        name: 'Favorite',
        component: () => import('@/views/Favorite'),
        meta: {title: '实案审核'}
    }
]

const createRouter = () =>
    new Router({
        scrollBehavior: () => ({y: 0}),
        routes: constantRoutes,
    })

const router = createRouter()

/**
 * 每次更改路由都会调用这个函数，所以这个函数开销必须尽可能小！
 * 参考 https://router.vuejs.org/zh/guide/advanced/navigation-guards.html
 * @param to 即将前往的路由
 * @param from 原来的路由
 * @param next resolve函数
 */
async function beforeChangeRoute(to, from, next) {
    document.title = (to.meta.title)+' - 航材保障实案管理系统'
    next()
}

router.beforeEach(beforeChangeRoute)

export function resetRouter() {
    const newRouter = createRouter()
    router.matcher = newRouter.matcher
}

export default router
